import * as echarts from '../../components/ec-canvas/echarts';
const db = wx.cloud.database();
const _ = db.command;
const $ = db.command.aggregate

function formateTime(time) {
  let date = new Date(Number(time));
  let y = date.getFullYear();
  let m = date.getMonth() + 1;
  let d = date.getDate();
  m = m < 10 ? "0" + m : m;
  d = d < 10 ? "0" + d : d;
  return `${m}-${d}`
}
// // 折线图
let chartLine;

function getLineOption() {
  let option = {
    title: {
      text: '每日报修统计',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '45',
      containLabel: true
    },
    dataZoom: [{
      type: 'slider',
      show: true,
      start: 0,
      end: 100,
      zoomLook: true,
      showDetail: false,
    }, ],
    xAxis: {
      type: 'category',
      data: [],
      axisTick: {
        alignWithLabel: true
      }
    },
    yAxis: {
      type: 'value',
    },
    series: [{
      name: '报修数量',
      data: [],
      type: 'line'
    }]
  };
  return option
}

function initChartLine1(canvas, width, height, dpr) {
  chartLine = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  });
  canvas.setChart(chartLine);
  chartLine.showLoading();
  let option = getLineOption();
  chartLine.setOption(option);
  return chartLine;
}
Page({
  data: {
    bar1: null,
    bar2: null,
    bar3: null,
    pie1: null,
    pie2: null,
    pie3: null,
    line1: {
      onInit: initChartLine1
    },
    line2:null,
    line3: null,
    active: "first",
    date: "",
    endDate: "" //限制年份
  },
  onChange(event) {
    this.setData({
      active: event.detail.name
    })
  },
  bindDateChange: async function (e) {
    this.setData({
      date: e.detail.value
    })
    this.setData({
      bar3: await this.getType(new Date(this.data.date, 0, 1).getTime(), new Date(this.data.date, 12, 31).getTime()),
      pie3: await this.getTypePro(new Date(this.data.date, 0, 1).getTime(), new Date(this.data.date, 12, 31).getTime()),
      line3:await this.getTypeLine2(this.data.date,12)
    })
  },
  async countType(condition) {
    const countResult = await db.collection("orderList").where(condition).count();
    const total = countResult.total;
    return total
  },
  async getType(start, end) {
    let data = [0, 0, 0, 0, 0];
    await db.collection('orderList').aggregate()
      .match({
        "completeTime": _.gte(start).and(_.lte(end))
      })
      .sortByCount('$problem_type')
      .end().then(res => {
        res.list.forEach(item => {
          switch (item._id) {
            case "air_condition":
              data[0] = item.count;
              break;
            case "network":
              data[1] = item.count;
              break;
            case "heater":
              data[2] = item.count;
              break;
            case "facilities":
              data[3] = item.count;
              break;
            case "other":
              data[4] = item.count;
              break;
          }
        })
      })
    return data;
  },
  async getTypePro(start, end) {
    let data = [{
        name: "空调",
        value: 0
      },
      {
        name: "网络",
        value: 0
      },
      {
        name: "热水器",
        value: 0
      },
      {
        name: "宿舍设施",
        value: 0
      },
      {
        name: "其他",
        value: 0
      },
    ]
    await db.collection('orderList').aggregate()
      .match({
        "completeTime": _.gte(start).and(_.lte(end))
      })
      .group({
        _id: '$problem_type',
        count: $.sum(1)
      })
      .end().then(res => {
        res.list.forEach(item => {
          switch (item._id) {
            case "air_condition":
              data[0].value = item.count;
              break;
            case "network":
              data[1].value = item.count;
              break;
            case "heater":
              data[2].value = item.count;
              break;
            case "facilities":
              data[3].value = item.count;
              break;
            case "other":
              data[4].value = item.count;
              break;
          }
        })
      })
    return data;
  },
  // 近30天的折线图
  async getTypeLine() {
    let xdata = [];
    let ydata = [];
    for (let index = 30; index >= 0; index--) {
      let start = new Date(new Date().toLocaleDateString()).getTime() - 1000 * 60 * 60 * 24 * index;
      let end = start + 24 * 60 * 60 * 1000 - 1;
      xdata.push(formateTime(start));
      let total = await this.countType({
        "completeTime": _.gte(start).and(_.lte(end))
      })
      ydata.push(total);
    }
    chartLine.setOption({
      xAxis: {
        data: xdata
      },
      series: [{
        data: ydata
      }]
    });
    chartLine.hideLoading();
  },
  // 获取一年的数据统计
  async getTypeLine2(year, month) {
    let xdata = [];
    let ydata = [];
    for (let index = 1; index <= month; index++) {
      xdata.push(`${index}月`);
      let start = new Date(year, index - 1, 1).getTime();
      let end = new Date(year, index, 0).getTime();
      let total = await this.countType({
        "completeTime": _.gte(start).and(_.lte(end))
      })
      ydata.push(total);
    }
    return {
      xdata,
      ydata
    }
  },
  onReady: async function () {
    let nowDate = new Date();
    // 获取近30天的数据
    this.setData({
      bar1: await this.getType(new Date(nowDate.toLocaleDateString()).getTime() - 1000 * 60 * 60 * 24 * 30, nowDate.getTime()),
      pie1: await this.getTypePro(new Date(nowDate.toLocaleDateString()).getTime() - 1000 * 60 * 60 * 24 * 30, nowDate.getTime()),
    })
    this.getTypeLine();
    // 获取今年的数据
    this.setData({
      bar2: await this.getType(new Date(nowDate.getFullYear(), 0, 1).getTime(), nowDate.getTime()),
      pie2: await this.getTypePro(new Date(nowDate.getFullYear(), 0, 1).getTime(), nowDate.getTime()),
      line2:await this.getTypeLine2(nowDate.getFullYear(), nowDate.getMonth() + 1)
    })
    // 获取近年的数据
    this.setData({
      date: nowDate.getFullYear() - 1,
      endDate: nowDate.getFullYear()-1
    })
    this.setData({
      bar3: await this.getType(new Date(this.data.date, 0, 1).getTime(), new Date(this.data.date, 12, 31).getTime()),
      pie3: await this.getTypePro(new Date(this.data.date, 0, 1).getTime(), new Date(this.data.date, 12, 31).getTime()),
      line3:await this.getTypeLine2(this.data.date,12)
    })
  }
});